package com.qiandw.enterprise.credit.controller

import javax.servlet.http.{HttpServletRequest, HttpServletResponse}

import com.qiandw.enterprise.credit.common.{SysExceptionHandleController, SysResp}
import com.qiandw.enterprise.credit.utils.RandomValidateCodeUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{RequestMapping, RequestParam, ResponseBody}
import org.springframework.web.servlet.ModelAndView
import com.qiandw.enterprise.credit._
import com.qiandw.enterprise.credit.listener.LoginEvent
import com.qiandw.enterprise.credit.service.BackstageUserSrv
import org.springframework.context.{ApplicationEventPublisher, ApplicationEventPublisherAware}
import com.qiandw.enterprise.credit.utils._

/**
  * 登录相关
  * Created by Draven on 2018/7/12.
  * Email:hjx@qiandw.com
  */
@Controller
@RequestMapping(value = Array("/passport"))
class LoginController extends CommonController with ApplicationEventPublisherAware {

  val logger = LoggerFactory.getLogger(classOf[LoginController])

  @Autowired
  var backstageUserSrv: BackstageUserSrv = _

  var eventPublisher: ApplicationEventPublisher = _

  @RequestMapping(value = Array("/login"))
  def toLoginPage(request: HttpServletRequest): ModelAndView = {
    toPage("/login")
  }

  /**
    * 获取验证码
    *
    * @param request
    * @param response
    */
  @RequestMapping(value = Array("/getVerify"))
  def getVerify(request: HttpServletRequest, response: HttpServletResponse): Unit = {
    try {
      response.setContentType("image/jpeg") //设置相应类型,告诉浏览器输出的内容为图片
      response.setHeader("Pragma", "No-cache") //设置响应头信息，告诉浏览器不要缓存此内容
      response.setHeader("Cache-Control", "no-cache")
      response.setDateHeader("Expire", 0)
      val randomValidateCode = new RandomValidateCodeUtil()
      randomValidateCode.getRandcode(request, response); //输出验证码图片方法
    } catch {
      case e: Exception => logger.error(e.getMessage)
    }
  }

  /**
    * 登录
    *
    * @param request
    * @param username
    * @param password
    * @param verifyCode
    * @return
    */
  @RequestMapping(value = Array("/doLogin"), produces = Array("application/json;charset=UTF-8"))
  @ResponseBody
  def doLogin(request: HttpServletRequest, @RequestParam("username") username: String, @RequestParam("password") password: String, @RequestParam("verifyCode") verifyCode: String): SysResp = {
    val sessionVerify = request.getSession.getAttribute("RANDOMVALIDATECODEKEY").toString
    if (!sessionVerify.equalsIgnoreCase(verifyCode)) {
      return SysResp(SYS_MSG_VERIFYCODE_ERROR)
    }
    val user = backstageUserSrv.getBackstageUserByUsernameAndPassword(username, Md5Util.md5(password))
    if (user == null) {
      SysResp(SYS_MSG_PWD_ERROR)
    } else {
      val ip = getIp(request)
      user.lastLoginIp = ip
      request.getSession.setAttribute(SESSION_USER_KEY, user)
      eventPublisher.publishEvent(new LoginEvent(user))
      SysResp(SYS_MSG_SUCCESS)
    }
  }

  /**
    * 注销
    *
    * @param request
    * @return
    */
  @RequestMapping(value = Array("/loginOut"))
  def loginOut(request: HttpServletRequest): ModelAndView = {
    request.getSession().setAttribute(SESSION_USER_KEY, null)
    toPage("/login")
  }

  override def setApplicationEventPublisher(applicationEventPublisher: ApplicationEventPublisher): Unit = {
    this.eventPublisher = applicationEventPublisher
  }
}
